<template>
  <div>
    <h1>导入发起工资计算
  </h1>
    <el-form :model="formData" ref="form" :rules="rules" label-width="80px" :inline="true">
      <el-form-item label="年份">
        <el-input v-model="formData.year"></el-input>
      </el-form-item>
      <el-form-item label="月份">
        <el-input v-model="formData.month"></el-input>
      </el-form-item>
      <el-form-item label="员工姓名">
        <el-input v-model="formData.emp"></el-input>
      </el-form-item>
      <el-form-item label="所在部门">
        <el-input v-model="formData.departmental"></el-input>
      </el-form-item>
      <el-form-item label="所在岗位">
        <el-input v-model="formData.postsname"></el-input>
      </el-form-item>
      <el-form-item label="提交人">
        <el-input v-model="formData.createdBy"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loadData">查询(指定/全部)数据</el-button>
        <el-button @click="batchUpdate" type="primary">更新</el-button>
        <el-button @click="toInsert" type="primary">发放工资处理</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="records" border stripe>
      <el-table-column type="index" width="50" />
      <el-table-column v-for="col in columns" :key="col.id" :label="col.label" :width="col.width">
        <template #default="scope">
          <el-input v-if="notEditColumns.some(item => item == col.id)" v-model="scope.row[col.id]" placeholder=""
            size="normal"></el-input>
          <span v-else>
            {{ scope.row[col.id] }}
          </span>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :destroy-on-close="true" :title="title" v-model="isVisible" width="60%">
      <span></span>
      <template #footer>
        <span>
          <router-view @ref-table="refTable" :data="data"></router-view>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import request from '@/api/request.js'
import router from '@/router'
import { ElMessage } from 'element-plus'

// 判断是否显示弹窗
let isVisible = ref(false)
let title = ref("")
let data = ref({})
let tableData = ref([])
let records = ref([])
let formData = ref({})

// 表格列定义 - 使用empName显示姓名
const columns = [
  { id: 'empName', label: '员工姓名' },  // 显示用姓名
  { id: 'departmental', label: '所在部门' },
  { id: 'postsname', label: '岗位' },
  { id: 'amountDue', label: '应发工资' },
  { id: 'paySalary', label: '绩效工资' },
  { id: 'subsidy', label: "补贴" },
  { id: 'socialSecurity', label: '当月缴纳社保' },
  { id: 'accumulationFund', label: '当月缴纳公积金' },
  { id: 'otherChargebacks', label: '当月其他扣款' },
  { id: 'personalIncomeTax', label: '当月应纳税所得额' },
  { id: 'actualAmount', label: '当月实发' },
  { id: 'releaseDate', label: '发放时间' },
  { id: 'createdBy', label: '提交人' },
  { id: 'issuanceStatus', label: '流程状态' }
]

const notEditColumns = ["amountDue","paySalary","otherChargebacks", "issuanceStatus"]
const rules = {}  // 可根据需要添加表单验证规则

// 弹窗相关方法
let refTable = () => {
  isVisible.value = false
  loadData()
}

let toInsert = () => {
  isVisible.value = true
  router.push("/salary/outsize/insert")
}

let toUpdate = (row) => {
  data.value = row
  isVisible.value = true
  router.push("/salary/outsize/update")
}

// 保存更新方法
const saveUpdate = () => {
  console.log(records.value)
  // 发起ajax请求逻辑
}

// 保存数据到数据库的方法
const saveDataToDatabase = () => {
  if (!records.value || records.value.length === 0) {
    alert('没有可保存的数据')
    return
  }

  request({
    url: '/outsize/saveBatch',
    method: 'post',
    data: records.value  // 包含原始emp值
  }).then(response => {
    if (response.success) {
      ElMessage.success('保存成功')
    } else {
      ElMessage.error(`保存失败：${response.message || '未知错误'}`)
    }
  }).catch(error => {
    console.error('保存数据出错：', error)
    ElMessage.error('网络错误，保存失败')
  })
}

// 加载初始数据
let loadDatas = () => {
  tableData.value = []
  return request({
    url: '/salary/setup/empdisposition/list',
    method: 'get'
  }).then(res => {
    const empList = res.data || []
    const detailRequests = empList.map(empItem => {
      // 新增empName字段用于显示，保留emp字段用于提交
      const tableItem = {
        emp: empItem.emp,  // 原始ID，用于提交
        empName: empItem.emp,  // 显示用姓名，后续会更新
        departmental: empItem.departmental,
        postsname: empItem.postsName,
        amountDue: empItem.baseSalary,
        paySalary: empItem.paySalary,
        subsidy: empItem.subsidy,
        socialSecurity: '',
        accumulationFund: '',
        otherChargebacks: '',
        personalIncomeTax: '',
        actualAmount: '',
        releaseDate: '',
        createdBy: '',
        issuanceStatus: ''
      }

      tableData.value.push(tableItem)

      return request({
        url: '/salary/setup/risks/list',
        method: 'get',
        params: {
          emp: empItem.emp,
          ...formData.value
        }
      }).then(detailRes => {
        const securityList = detailRes.data || []
        const detailData = securityList.find(item => item.emp === empItem.emp) || {}
        const targetItem = tableData.value.find(item => item.emp === empItem.emp)

        if (targetItem) {
          let socialSecuritySum = (detailData.pensionInsuranceIndividual || 0) +
            (detailData.healthInsuranceIndividual || 0) +
            (detailData.unemploymentInsuranceIndividual || 0)
          targetItem.socialSecurity = socialSecuritySum
          targetItem.accumulationFund = detailData.housingProvidentIndividual || 0
          targetItem.otherChargebacks = 0
          targetItem.personalIncomeTax = 0
          targetItem.actualAmount = (targetItem.amountDue || 0) + (targetItem.paySalary || 0) +
            (targetItem.subsidy || 0) - socialSecuritySum -
            targetItem.otherChargebacks - targetItem.personalIncomeTax
          targetItem.issuanceStatus = "未发放"
        }

        return tableData.value
      })
    })

    return Promise.all(detailRequests).then(finalTableData => {
      records.value = finalTableData[0] || []
      loadDataset(records.value)  // 加载完数据后立即执行loadDataset
      return records.value
    })
  }).catch(error => {
    console.error('数据加载失败:', error)
  })
}

// 查询数据方法
let loadData = () => {
  request({
    url: '/outsize/find',
    method: 'get',
    params: { ...formData.value }
  }).then(res => {
    // 为每条记录添加empName字段，初始值等于emp
    const data = res.data || []
    records.value = data.map(item => ({
      ...item,
      empName: item.emp  // 初始显示用名称
    }))
    console.log('从后端获取的列表数据：', records.value)
    loadDataset(records.value)  // 数据加载完成后执行loadDataset
  }).catch(error => {
    console.error('查询列表数据失败:', error)
    ElMessage.error('查询失败，请重试')
  })
}

// 批量更新方法
const batchUpdate = () => {
  if (!records.value || records.value.length === 0) {
    ElMessage.warning('没有可修改的数据')
    return
  }

  if (!confirm('确定要批量修改选中的数据吗？')) {
    return
  }

  // 发送包含原始emp值的数据
  request({
    url: '/outsize/updatelist',
    method: 'put',
    data: records.value
  }).then(response => {
    if (!response.success) {
      ElMessage.success('批量修改成功')
      loadData()  // 刷新表格数据
    } else {
      ElMessage.error(`批量修改失败：${response.message || '未知错误'}`)
    }
  }).catch(error => {
    console.error('批量修改出错：', error)
    ElMessage.error('网络错误，批量修改失败')
  })
}

// 加载员工姓名并更新显示，不修改原始emp值
let loadDataset = (tableRecords) => {
  tableRecords.forEach(async (record, index) => {
    try {
      const response = await request({
        url: '/into/getByIds',
        method: 'get',
        params: {
          id: record.emp  // 使用原始emp值（ID）查询
        }
      })
      
      // 只更新显示用的empName字段，不修改提交用的emp字段
      if (response.data && response.data.employeeName) {
        tableRecords[index].empName = response.data.employeeName
      }
    } catch (error) {
      console.error(`获取员工${record.emp}信息失败:`, error)
    }
  })
}

// 初始加载数据
loadData()
</script>

<style scoped></style>
